package com.zz.util;

import java.io.File;
import java.io.IOException;
import java.net.ConnectException;


import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;


public class Doc2PdfUtil {
    public void createPDF(String sourceFile, String destFile) {
        // String OpenOffice_HOME = "D:/Program Files/OpenOffice.org 3";//
        // 这里是OpenOffice的安装目录,C:\Program Files (x86)\OpenOffice 4
        String OpenOffice_HOME = "C:\\Program Files (x86)\\OpenOffice 4\\";
        Process pro = null;
        try {
            String command = OpenOffice_HOME
                    + "program\\soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;StarOffice.ServiceManager\" -nofirststartwizard";
            pro = Runtime.getRuntime().exec(command);
            File inputFile = new File(sourceFile);
            // 如果目标路径不存在, 则新建该路径
            File outputFile = new File(destFile);
            if (!outputFile.getParentFile().exists()) {
                outputFile.getParentFile().mkdirs();
            }

            // connect to an OpenOffice.org instance running on port 8100
            OpenOfficeConnection connection = new SocketOpenOfficeConnection(
                    "127.0.0.1", 8100);
            connection.connect();

            // convert
            DocumentConverter converter = new OpenOfficeDocumentConverter(
                    connection);
            converter.convert(inputFile, outputFile);

            // close the connection
            connection.disconnect();
            pro.destroy();
        } catch (ConnectException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//    public static void main(String[] args) {
//        createPDF("C:\\Users\\Administrator\\Desktop\\test.doc", "C:\\Users\\Administrator\\Desktop\\test.pdf");
//    }
}
